<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="手环MAC地址" prop="wb_mac">
        <el-input
          v-model="queryParams.wb_mac"
          placeholder="请输入手环MAC地址"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="网关MAC地址" prop="gw_mac">
        <el-input
          v-model="queryParams.gw_mac"
          placeholder="请输入网关MAC地址"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最小RSSI" prop="min_rssi">
        <el-input-number
          v-model="queryParams.min_rssi"
          :min="-150"
          placeholder="请输入最小RSSI"
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="查询时间(s)" prop="time">
        <el-input
          v-model="queryParams.time"
          placeholder="请输入查询时间(秒)"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="时间范围" prop="time_range">
        <el-date-picker
          v-model="queryParams.time_range"
          type="daterange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :default-value="[new Date(Date.now() - 60 * 1000), new Date()]"
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
      <el-button
        type="primary"
        icon="Download"
        @click="handleExport"
        style="margin-left: 10px"
        >导出（40个）</el-button
      >
    </el-row>
    <!-- v-loading="loading" -->
    <el-table
      :data="wristbandLists"
      size="small"
      :loading-options="{ background: 'rgba(0, 0, 0, 0.3)' }"
    >
      <!-- <el-table-column label="序号" width="55" type="index" align="center">
        <template #default="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="序列号" align="center" prop="idx" />
      <el-table-column
        label="手环MAC地址"
        width="150"
        align="center"
        prop="mac"
      />
      <el-table-column label="心率" align="center" prop="hr">
        <template #default="scope">
          {{ scope.row.hr }} (
          <b v-if="scope.row?.fake_hr == 1" style="color: #f56c6c">1</b>
          <b v-else style="color: #67c23a">0</b> )
          <!-- <el-tag v-if="scope.row?.fake_hr==0" type="success" effect="dark">{{ scope.row.fake_hr }}</el-tag>
        <el-tag v-else type="error" effect="dark">{{ scope.row.fake_hr || '0' }}</el-tag> -->
          <!-- <b style="color:#F56C6C">{{ scope.row.fake_hr || '0' }}</b> ) #67c23a -->
        </template>
      </el-table-column>
      <el-table-column label="步数" align="center" prop="steps">
        <template #default="scope">
          <b :style="{ color: getStepsColor(scope.row.steps) }">
            {{ scope.row?.steps || 0 }}
          </b>
        </template>
      </el-table-column>
      <el-table-column
        label="运动强度"
        width="150"
        align="center"
        prop="motion"
      >
        <template #default="scope">
          <b
            :style="{
              color:
                scope.row?.motion && scope.row?.motion > 0
                  ? 'inherit'
                  : '#F56C6C',
            }"
          >
            {{
              scope.row?.motion ? parseFloat(scope.row.motion).toFixed(6) : 0
            }}
          </b>
        </template>
      </el-table-column>
      <el-table-column
        label="运动强度方差"
        width="150"
        align="center"
        prop="motion_variance"
      >
        <template #default="scope">
          <b
            :style="{
              color:
                scope.row?.motion_variance && scope.row?.motion_variance > 0
                  ? 'inherit'
                  : '#F56C6C',
            }"
          >
            {{
              scope.row?.motion_variance
                ? parseFloat(scope.row.motion_variance).toFixed(6)
                : 0
            }}
          </b>
        </template>
      </el-table-column>
      <el-table-column label="温度" align="center" prop="temperature">
        <template #default="scope">
          <b :style="{ color: getTemperatureColor(scope.row?.temperature) }">
            {{ scope.row?.temperature || 0 }}
          </b>
        </template>
      </el-table-column>
      <el-table-column label="区角豆1" align="center" prop="beacon1">
        <template #default="scope">
          <b
            :style="{
              color:
                scope.row?.beacon1 && scope.row?.beacon1 > 0
                  ? '#67c23a'
                  : '#F56C6C',
            }"
          >
            {{ scope.row?.beacon1 || 0 }}
          </b>
        </template>
      </el-table-column>
      <el-table-column label="区角豆2" align="center" prop="beacon2">
        <template #default="scope">
          <b
            :style="{
              color:
                scope.row?.beacon2 && scope.row?.beacon2 > 0
                  ? '#67c23a'
                  : '#F56C6C',
            }"
          >
            {{ scope.row?.beacon2 || 0 }}
          </b>
        </template>
      </el-table-column>
      <el-table-column label="区角豆3" align="center" prop="beacon3">
        <template #default="scope">
          <b
            :style="{
              color:
                scope.row?.beacon3 && scope.row?.beacon3 > 0
                  ? '#67c23a'
                  : '#F56C6C',
            }"
          >
            {{ scope.row?.beacon3 || 0 }}
          </b>
        </template>
      </el-table-column>
      <!-- <el-table-column label="x" align="center" prop="acc_x" />
    <el-table-column label="y" align="center" prop="acc_y" />
    <el-table-column label="z" align="center" prop="acc_z" /> -->
      <el-table-column label="信号" align="center" sortable prop="rssi">
        <template #default="scope">
          <b :style="{ color: getRssiColor(scope.row?.rssi || 0) }">
            {{ scope.row?.rssi || "--" }}
          </b>
        </template>
      </el-table-column>
      <el-table-column label="格式" align="center" sortable prop="format" />
      <el-table-column
        label="网关MAC地址"
        width="150"
        align="center"
        prop="gw_mac"
        sortable
        fixed="right"
      />
      <el-table-column
        label="时间"
        align="center"
        prop="time"
        width="180"
        sortable
        fixed="right"
      >
        <template #default="scope">
          <span v-if="scope.row.time">
            {{ formartIOSDate(scope.row.time) || "--" }}
            (
            <span style="color: #67c23a">{{
              formatOnlineTime(formartIOSDate(scope.row.time))
            }}</span>
            )
          </span>
          <span v-else> -- </span>
          <!-- {{ scope.row.time?formartIOSDate(scope.row.time) : '--'}} -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup name="Post">
import * as XLSX from "xlsx";
import { getWristbandAdvByMacLast } from "@/api/system/firmware/wb";
import { reactive } from "vue";
import { getAuthRole } from "@/api/system/user";
import {
  getCurrentDayDate,
  formartIOSDate,
  formatDate,
} from "@/utils/dateFormart";
const { proxy } = getCurrentInstance();
const wristbandLists = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const isFetching = ref(false);
let intervalId = null;
onMounted(() => {
  loading.value = true;
  // getList();
  // intervalId = setInterval(() => {
  //   loading.value = true;
  //   getList();
  // }, 1500);
});

onUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId);
    wristbandLists.value = [];
  }
});
const formatOnlineTime = (time) => {
  if (!time) {
    return " -- ";
  }
  const countTime = formatDate(time);
  return countTime || " -- ";
};
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 120,
    wb_mac: undefined,
    gw_mac: undefined,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

const queryParamsData = reactive({});

// 定义计算步数颜色的方法
const getStepsColor = (steps) => {
  if (steps && steps > 4500) {
    return "#67c23a";
  } else if (steps && steps > 0) {
    return "inherit";
  } else {
    return "#F56C6C";
  }
};
const getTemperatureColor = (temperature) => {
  if (temperature && temperature > 37.5) {
    return "#F56C6C";
  } else if (temperature && temperature >= 35.5) {
    return "#67c23a";
  } else {
    return "#E6A23C";
  }
};
const getRssiColor = (rssi) => {
  if (rssi && rssi > -40) {
    return "#67c23a";
  } else if (rssi && rssi >= -80) {
    return "#E6A23C";
  } else {
    return "#F56C6C";
  }
};
/** 查询网关列表 */
function getList() {
  if (isFetching.value) return;
  isFetching.value = true;
  // loading.value = true;
  console.log("手环实时数据 入参 queryParamsData.value", queryParamsData.value);
  getWristbandAdvByMacLast(queryParamsData.value)
    .then((response) => {
      console.log("手环实时数据 出参", response.data);
      wristbandLists.value = response.data.data;
      total.value = response.data.total;
    })
    .finally(() => {
      isFetching.value = false;
      loading.value = false;
    });
}

/** 搜索按钮操作 */
function handleQuery() {
  console.log("手环实时数据 入参 ---------------");
  if (intervalId) {
    clearInterval(intervalId);
    wristbandLists.value = [];
  }
  //手环MAC地址和网关MAC地址都不填则不查询
  if (!queryParams.value.wb_mac && !queryParams.value.gw_mac) {
    proxy.$message.error("请输入手环MAC地址或网关MAC地址进行查询！");
    return;
  }
  queryParams.value.pageNum = 1;
  // loading.value = true;
  queryParamsData.value = {
    ...queryParams.value,
  };
  getList();
  intervalId = setInterval(() => {
    // loading.value = true;
    getList();
  }, 1500);
}

/** 重置按钮操作 */
function resetQuery() {
  // dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}


function handleExport() {
  if (!wristbandLists.value.length) {
    proxy.$modal.msgError("没有可导出的数据");
    return;
  }

  // 按信号强度和时间排序
  const sortedData = [...wristbandLists.value]
    .sort((a, b) => {
      // 先按信号强度降序
      const rssiDiff = (b.rssi || -1000) - (a.rssi || -1000);
      if (rssiDiff !== 0) return rssiDiff;

      // 信号相同按时间降序
      return new Date(b.time) - new Date(a.time);
    })
    // .slice(0, 40); // 取前40条

  const exportData = sortedData.map((item) => ({
    mac: item.mac,
    rssi: item.rssi,
    gw_mac: item.gw_mac,
    time: formartIOSDate(item.time),
  }));

  const ws = XLSX.utils.json_to_sheet(exportData);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "手环数据");

  const excelBuffer = XLSX.write(wb, { bookType: "xlsx", type: "array" });
  const data = new Blob([excelBuffer], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",
  });
  const url = window.URL.createObjectURL(data);
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", `手环数据_${new Date().getTime()}.xlsx`);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
</script>
<style lang="scss" scoped>
.list-group-top-none .list-group-striped > .list-group-item {
  border-top: none;
}
.wristbandDetail {
  :deep(.pagination-container .el-pagination) {
    right: 20px;
  }
}
</style>
